<template>
    <div class="container">
        <van-sticky>
            <van-nav-bar title="选择城市"  left-arrow @click-left="goBack" />
            <van-search v-model="search" placeholder="请输入搜索关键词" />
        </van-sticky>
        <van-index-bar :sticky='false'>
            <van-index-anchor :index="name" v-for="(item, name) in cities" :key="name">
                <b>{{ name }}</b>
                <p v-for="(a, b) in item" :key="b" @click="getCity(a)">{{ a.label }}</p>
            </van-index-anchor>
        </van-index-bar>
    </div>
</template>

<script>
import { city } from "@/api/user";
export default {
    data() {
        return {
            FirstPin: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L",
                "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z",],
            cities: {},
            search: ''
        };
    },
    async mounted() {
        const res = await city();
        var cities = res.data.body
        // console.log(cities)
        let cityName = {};
        //循环26个字母的数组
        this.FirstPin.forEach(item => {
            cityName[item] = [];
            cities.forEach(el => {
                //对比开头字母是否对应
                let first = el.pinyin.substring(0, 1).toUpperCase();
                if (first == item) {
                    cityName[item].push(el);
                }
            });
        });
        console.log(cityName)
        this.$nextTick(() => {
            this.cities = cityName;
        })
    },
    methods: {
        goBack() {
            this.$router.back()
        },
        getCity(city){
            console.log(city)
            this.$router.push({
                path:"/house",
                query:{
                    city
                }
            })
            // this.$emit()
            // this.$router.back()
        }
    }

};
</script>

<style scoped lang="less">
* {
    background-color: #fff;
}
</style>
